//
//  GNRHelper.m
//  UUIM
//
//  Created by LvYuan on 2017/4/5.
//  Copyright © 2017年 UUPaotui. All rights reserved.
//

#import "GNRHelper.h"
#include <sys/sysctl.h>

static GNRHelper * help = nil;
@implementation GNRHelper
+ (void)goCheckSetting{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {
            
        }];
    }
}
+ (GNRHelper *)gNRHelpShare {
    if (!help) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            help = [[GNRHelper alloc] init];
        });
    }
    return help;
}

//创建本地缓存
+ (void)userDefault:(NSString *)object key:(NSString *)key {
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    [user setObject:object forKey:key];
}
//获取缓存
+ (id)getUserObjectKey:(id)key {
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

+ (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

//保存图片到本地并获取图片路径
+ (NSString *)filePathWithImageData:(NSData *)data type:(NSString *)type{
    NSString * fileName = [NSString stringWithFormat:@"HEAD"];
    //图片保存的路径
    NSString * DocumentsPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/updatePhoto"];
    //文件管理器
    NSFileManager * fileManager=[NSFileManager defaultManager];
    //保存到沙盒
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    //保存为jpg
    NSString * path=[DocumentsPath stringByAppendingString:[NSString stringWithFormat:@"/%@.%@",fileName,type]];
    [fileManager createFileAtPath:path contents:data attributes:nil];
    [data writeToFile:path atomically:YES];
    NSLog(@"保存地址 %@",path);
    return  path;
}

+ (NSComparisonResult)compareOneDay:(NSString *)oneDay withAnotherDay:(NSString *)anotherDay{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *dateA = [dateFormatter dateFromString:oneDay];
    NSDate *dateB = [dateFormatter dateFromString:anotherDay];
    NSComparisonResult result = [dateA compare:dateB];
    return result;
}

+ (BOOL)isValidDateStr:(NSString *)dateStr{
    NSString *pattern = @"^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:dateStr];
    return isMatch;
}

+ (NSString *)valueFromUrl:(NSString *)url param:(NSString *)paramName
{
    if (![paramName hasSuffix:@"="]) {
        paramName = [NSString stringWithFormat:@"%@=", paramName];
    }
    
    NSString *str = nil;
    NSRange   start = [url rangeOfString:paramName];
    if (start.location != NSNotFound) {
        // confirm that the parameter is not a partial name match
        unichar  c = '?';
        if (start.location != 0) {
            c = [url characterAtIndex:start.location - 1];
        }
        if (c == '?' || c == '&' || c == '#') {
            NSRange     end = [[url substringFromIndex:start.location + start.length] rangeOfString:@"&"];
            NSUInteger  offset = start.location + start.length;
            str = end.location == NSNotFound ?
            [url substringFromIndex:offset] :
            [url substringWithRange:NSMakeRange(offset, end.location)];
            str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
    }
    return str;
}

+ (NSDictionary*)dictionaryFromQuery:(NSString*)query usingEncoding:(NSStringEncoding)encoding{
    NSCharacterSet* delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"&;"];
    NSMutableDictionary* pairs = [NSMutableDictionary dictionary];
    NSScanner* scanner = [[NSScanner alloc] initWithString:query];
    while (![scanner isAtEnd]) {
        NSString* pairString = nil;
        [scanner scanUpToCharactersFromSet:delimiterSet intoString:&pairString];
        [scanner scanCharactersFromSet:delimiterSet intoString:NULL];
        NSArray* kvPair = [pairString componentsSeparatedByString:@"="];
        if (kvPair.count == 2) {
            NSString* key = [[kvPair objectAtIndex:0]
                             stringByReplacingPercentEscapesUsingEncoding:encoding];
            NSString* value = [[kvPair objectAtIndex:1]
                               stringByReplacingPercentEscapesUsingEncoding:encoding];
            [pairs setObject:value forKey:key];
        }
    }
    
    return [NSDictionary dictionaryWithDictionary:pairs];
}

/**
 将带有 {}
 
 @param str 的替换为标红字体
 @return attstring
 */
+ (NSAttributedString *)replaceBracketsFromString:(NSString *)str textColor:(UIColor *)textColor fontSize:(CGFloat)fontSize{
    if (str==nil) {
        return nil;
    }
    
    NSAttributedString * attStr = [GNRHelper attStringForStr:str ranges:[GNRHelper rangesForString:str] textColor:textColor font:[UIFont systemFontOfSize:fontSize] lineSpace:4 hasLine:NO];
    
    if (attStr==nil) {
        return [[NSMutableAttributedString alloc]initWithString:[GNRHelper getTotalString:str]];
    }
    
    return attStr;
}

+ (NSArray *)rangesForString:(NSString *)string{
    NSMutableArray * ranges = [NSMutableArray array];
    NSMutableArray * locs = [NSMutableArray array];
    if (string.length>0) {
        //locs
        NSUInteger count = 0;
        for (int i=0; i<string.length; i++) {
            char ch = [string characterAtIndex:i];
            if (ch == '{') {
                [locs addObject: @(i - 2*count++).stringValue];
            }
        }
        
        NSMutableArray * values = [NSMutableArray array];
        //ranges
        NSArray * strArr = [string componentsSeparatedByString:@"{"];
        [strArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString * subValue = obj;
            if (idx!=0) {
                NSArray * subArr = [subValue componentsSeparatedByString:@"}"];
                if (subArr.count==2&&subArr.firstObject) {
                    [values addObject:subArr.firstObject];
                }
            }
        }];
        
        //还原字符串
        string = [GNRHelper getTotalString:string];
        
        [values enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj) {
                NSString * value = obj;
                NSRange range = NSMakeRange([locs[idx] intValue], value.length);
                [ranges addObject:NSStringFromRange(range)];
            }
        }];
    }
    return ranges;
}

+ (NSString *)getTotalString:(NSString *)string{
    NSString * totalStr = [string stringByReplacingOccurrencesOfString:@"{" withString:@""];
    totalStr = [totalStr stringByReplacingOccurrencesOfString:@"}" withString:@""];
    return totalStr;
}

+ (NSAttributedString *)attStringForStr:(NSString *)string ranges:(NSArray <NSString *> *)ranges textColor:(UIColor *)textColor font:(UIFont*)font lineSpace:(CGFloat)lineSpace hasLine:(BOOL)hasLine{
    if (string.length&&ranges.count) {
        NSString * totalStr = [GNRHelper getTotalString:string];
        
        NSMutableAttributedString * attS = [[NSMutableAttributedString alloc]initWithString:totalStr];
        
        [ranges enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj) {
                NSRange range = NSRangeFromString(obj);
                if (ranges) {
                    [attS addAttribute:NSForegroundColorAttributeName value:textColor range:range];
                    [attS addAttribute:NSFontAttributeName value:font range:range];
                    if (hasLine) {
                        [attS addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
                    }
                }
            }
        }];
        
        NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:lineSpace];
        paragraphStyle.alignment = NSTextAlignmentCenter;
        [attS addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [totalStr length])];
        
        return attS;
    }
    return nil;
}

//是否有下划线
+ (NSAttributedString *)replaceBracketsFromString:(NSString *)str textColor:(UIColor *)textColor font:(UIFont *)font hasLine:(BOOL)hasLine{
    if (str==nil) {
        return nil;
    }
    
    NSAttributedString * attStr = [GNRHelper attStringForStr:str ranges:[GNRHelper rangesForString:str] textColor:textColor font:font lineSpace:4 hasLine:hasLine];
    
    if (attStr==nil) {
        return [[NSMutableAttributedString alloc]initWithString:[GNRHelper getTotalString:str]];
    }
    
    return attStr;
}

/**
 将带有 {} 替换为富文本
 */
+ (NSAttributedString *)replaceBracketsFromString:(NSString *)str textColor:(UIColor *)textColor font:(UIFont *)font lineSpace:(CGFloat)lineSpace{
    if (str==nil) {
        return nil;
    }
    
    NSAttributedString * attStr = [GNRHelper attStringForStr:str ranges:[GNRHelper rangesForString:str] textColor:textColor font:font lineSpace:lineSpace hasLine:NO];
    
    if (attStr==nil) {
        return [[NSMutableAttributedString alloc]initWithString:[GNRHelper getTotalString:str]];
    }
    
    return attStr;
    
}
+ (NSString *)getUrlWithBaseUrl:(NSString *)baseUrl parameters:(NSDictionary *)parameters{
    // 初始化参数变量
    NSString *str = @"";
    // 快速遍历参数数组
    for(id key in parameters) {
        NSLog(@"key :%@  value :%@", key, [parameters objectForKey:key]);
        str = [str stringByAppendingString:key];
        str = [str stringByAppendingString:@"="];
        str = [str stringByAppendingString:[parameters objectForKey:key]];
        str = [str stringByAppendingString:@"&"];
    }
    // 处理多余的&以及返回含参url
    if (str.length > 1) {
        // 去掉末尾的&
        str = [str substringToIndex:str.length - 1];
        // 返回含参url
        str = [NSString stringWithFormat:@"%@?%@",baseUrl,str];
        NSLog(@"WEBURL: %@",str);
        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"WEBURL ENCODE: %@",str);
        
        return str;
    }
    return nil;
}


+ (BOOL)uIsAvailablePassword:(NSString *)password {
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,30}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
}

+ (UIImage *)imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    
    UIImage *newImage = nil;
    
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    
    CGFloat height = imageSize.height;
    
    CGFloat targetWidth = size.width;
    
    CGFloat targetHeight = size.height;
    
    CGFloat scaleFactor = 0.0;
    
    CGFloat scaledWidth = targetWidth;
    
    CGFloat scaledHeight = targetHeight;
    
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            
            scaleFactor = widthFactor;
            
        }
        
        else{
            
            scaleFactor = heightFactor;
            
        }
        
        scaledWidth = width * scaleFactor;
        
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            
        }
        
    }
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 3.0);
    
    CGRect thumbnailRect = CGRectZero;
    
    thumbnailRect.origin = thumbnailPoint;
    
    thumbnailRect.size.width = scaledWidth;
    
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
        
    }
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

/*手机号码验证 MODIFIED BY HELENSONG*/
+ (BOOL)isMobileNumber:(NSString *)mobileNum{
    NSString *pattern = @"^1+[345678]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:mobileNum];
    return isMatch;
}

+ (BOOL)isUrl:(NSString *)url{
    NSString * urlString = @"^(\\w+:\\/\\/)?\\w+(\\.\\w+)+.*$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlString];
    return [emailTest evaluateWithObject:url];
}

+ (NSString*)standardTimeForFile:(NSDate*)date{
    NSDateFormatter *Formatter=[[NSDateFormatter alloc]init];
    [Formatter setDateFormat:@"yyyy_MM_dd_HH_mm_ss"];
    return [Formatter stringFromDate:date];
}

+ (NSString*)standardDateForFile:(NSDate*)date{
    NSDateFormatter *Formatter=[[NSDateFormatter alloc]init];
    [Formatter setDateFormat:@"yyyy_MM_dd"];
    return [Formatter stringFromDate:date];
}

//时间戳-字符串日期
+ (NSString*)dateFormatForTime:(NSTimeInterval)time{
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *Formatter=[[NSDateFormatter alloc]init];
    [Formatter setDateFormat:@"yyyy-MM-dd"];
    return [Formatter stringFromDate:date];
}

+ (NSString*)timeStrFormatForTime:(NSTimeInterval)time{
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *Formatter=[[NSDateFormatter alloc]init];
    [Formatter setDateFormat:@"HH:mm:ss"];
    return [Formatter stringFromDate:date];
}

+ (NSString*)standardTime:(NSDate*)date{
    NSDateFormatter *Formatter=[[NSDateFormatter alloc]init];
    [Formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [Formatter stringFromDate:date];
}
//获取当前时间
+ (NSString*)getCurrentTime:(NSDate*)date dateFormate:(NSString *)dateFormate{
    NSDateFormatter *Formatter=[[NSDateFormatter alloc]init];
    [Formatter setDateFormat:dateFormate];
    return [Formatter stringFromDate:date];
}

+ (NSString*)showDetailTime:(NSTimeInterval) msglastTime{
    return [GNRHelper showTime:msglastTime showDetail:YES];
}

+ (NSString*)showTime:(NSTimeInterval) msglastTime showDetail:(BOOL)showDetail
{
    //今天的时间
    NSDate * nowDate = [NSDate date];
    NSDate * msgDate = [NSDate dateWithTimeIntervalSince1970:msglastTime];
    NSString *result = nil;
    NSCalendarUnit components = (NSCalendarUnit)(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitHour | NSCalendarUnitMinute);
    NSDateComponents *nowDateComponents = [[NSCalendar currentCalendar] components:components fromDate:nowDate];
    NSDateComponents *msgDateComponents = [[NSCalendar currentCalendar] components:components fromDate:msgDate];
    
    NSInteger hour = msgDateComponents.hour;
    NSTimeInterval gapTime = -msgDate.timeIntervalSinceNow;
    double onedayTimeIntervalValue = 24*60*60;  //一天的秒数
    result = [GNRHelper getPeriodOfTime:hour withMinute:msgDateComponents.minute];
    if (hour > 12)
    {
        hour = hour - 12;
    }
    if (gapTime < onedayTimeIntervalValue * 3) {
        int gapDay = gapTime/(60*60*24) ;
        if(gapDay == 0) //在24小时内,存在跨天的现象. 判断两个时间是否在同一天内
        {
            BOOL isSameDay = msgDateComponents.day == nowDateComponents.day;
            result = isSameDay ? [[NSString alloc] initWithFormat:@"%@ %zd:%02d",result,hour,(int)msgDateComponents.minute] : (showDetail?  [[NSString alloc] initWithFormat:@"昨天%@ %zd:%02d",result,hour,(int)msgDateComponents.minute] : @"昨天");
        }
        else if(gapDay == 1)//昨天
        {
            result = showDetail?  [[NSString alloc] initWithFormat:@"昨天%@ %zd:%02d",result,hour,(int)msgDateComponents.minute] : @"昨天";
        }
        else if(gapDay == 2) //前天
        {
            result = showDetail? [[NSString alloc] initWithFormat:@"前天%@ %zd:%02d",result,hour,(int)msgDateComponents.minute] : @"前天";
        }
    }
    else if([nowDate timeIntervalSinceDate:msgDate] < 7 * onedayTimeIntervalValue)//一周内
    {
        NSString *weekDay = [GNRHelper weekdayStr:msgDateComponents.weekday];
        result = showDetail? [weekDay stringByAppendingFormat:@"%@ %zd:%02d",result,hour,(int)msgDateComponents.minute] : weekDay;
    }
    else//显示日期
    {
        NSString *day = [NSString stringWithFormat:@"%zd-%zd-%zd", msgDateComponents.year, msgDateComponents.month, msgDateComponents.day];
        result = showDetail? [day stringByAppendingFormat:@" %@ %zd:%02d",result,hour,(int)msgDateComponents.minute]:day;
    }
    return result;
}

#pragma mark - Private

+ (NSString *)getPeriodOfTime:(NSInteger)time withMinute:(NSInteger)minute
{
    NSInteger totalMin = time *60 + minute;
    NSString *showPeriodOfTime = @"";
    if (totalMin > 0 && totalMin <= 5 * 60)
    {
        showPeriodOfTime = @"凌晨";
    }
    else if (totalMin > 5 * 60 && totalMin < 12 * 60)
    {
        showPeriodOfTime = @"上午";
    }
    else if (totalMin >= 12 * 60 && totalMin <= 18 * 60)
    {
        showPeriodOfTime = @"下午";
    }
    else if ((totalMin > 18 * 60 && totalMin <= (23 * 60 + 59)) || totalMin == 0)
    {
        showPeriodOfTime = @"晚上";
    }
    return showPeriodOfTime;
}

+(NSString*)weekdayStr:(NSInteger)dayOfWeek
{
    static NSDictionary *daysOfWeekDict = nil;
    daysOfWeekDict = @{@(1):@"星期日",
                       @(2):@"星期一",
                       @(3):@"星期二",
                       @(4):@"星期三",
                       @(5):@"星期四",
                       @(6):@"星期五",
                       @(7):@"星期六",};
    return [daysOfWeekDict objectForKey:@(dayOfWeek)];
}
/*!
 * @brief 把格式化的JSON格式的字符串转换成obj
 * @param jsonString JSON格式的字符串
 * @return 返回obj
 */
+ (id)objWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    id obj = [NSJSONSerialization JSONObjectWithData:jsonData
                                             options:NSJSONReadingMutableContainers
                                               error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return obj;
}

+ (NSString *)appVersion{
    NSString * path=[[NSBundle mainBundle]pathForResource:@"Info" ofType:@"plist"];
    NSDictionary * info=[NSDictionary dictionaryWithContentsOfFile:path];
    NSString * versionString=[info objectForKey:@"CFBundleShortVersionString"];
    return versionString;
}

+ (NSString *)getAppVersionDesc{
    NSString * path=[[NSBundle mainBundle]pathForResource:@"Info" ofType:@"plist"];
    NSDictionary * info=[NSDictionary dictionaryWithContentsOfFile:path];
    NSString * versionString=[info objectForKey:@"CFBundleShortVersionString"];
    NSString * bundleVersion=[info objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"v%@(%@)",versionString,bundleVersion];
}

//字典转json格式字符串：
+ (NSString*)dictToJson:(NSDictionary *)dic{
    //NSJSONWritingPrettyPrinted  是有换位符的。
    //如果NSJSONWritingPrettyPrinted 是nil 的话 返回的数据是没有 换位符的
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

//获取设备 iPhone8,2 等
+ (NSString *)device{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    return [GNRHelper getCurrentDeviceModel:platform];
}

+ (void)showAlertViewController:(UIViewController *)viewController title:(NSString *)title  cancelTitle:(NSString *)canceltitle affireTitle:(NSString *)affireTitle affireAction:(void (^)())affireAction{

    UIAlertController * alterController = [UIAlertController alertControllerWithTitle:title message:@"" preferredStyle:UIAlertControllerStyleAlert];
    if (canceltitle) {
        UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:canceltitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alterController addAction:actionCancel];
    }
    if (affireTitle) {
        UIAlertAction * actionAffire = [UIAlertAction actionWithTitle:affireTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (affireAction) affireAction();
        }];
        [alterController addAction:actionAffire];
    }
    [viewController presentViewController:alterController animated:YES completion:nil];
}

//获得设备型号
+ (NSString *)getCurrentDeviceModel:(NSString *)platform
{
    // iPhone
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone2G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone3GS";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone4";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone4";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone4";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone4S";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone5";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone5";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone5c";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone5c";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone5s";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone5s";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone6";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone6Plus";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone6sPlus";
    if ([platform isEqualToString:@"iPhone8,3"]) return @"iPhoneSE";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhoneSE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone7Plus";
    
    //iPod Touch
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPodTouch";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPodTouch2G";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPodTouch3G";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPodTouch4G";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPodTouch5G";
    if ([platform isEqualToString:@"iPod7,1"])   return @"iPodTouch6G";
    
    //iPad
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad2";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad2";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad2";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad2";
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad3";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad3";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad3";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad4";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad4";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad4";
    
    //iPad Air
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPadAir";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPadAir";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPadAir";
    if ([platform isEqualToString:@"iPad5,3"])   return @"iPadAir2";
    if ([platform isEqualToString:@"iPad5,4"])   return @"iPadAir2";
    
    //iPad mini
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPadmini1G";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPadmini1G";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPadmini1G";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPadmini2";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPadmini2";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPadmini2";
    if ([platform isEqualToString:@"iPad4,7"])   return @"iPadmini3";
    if ([platform isEqualToString:@"iPad4,8"])   return @"iPadmini3";
    if ([platform isEqualToString:@"iPad4,9"])   return @"iPadmini3";
    if ([platform isEqualToString:@"iPad5,1"])   return @"iPadmini4";
    if ([platform isEqualToString:@"iPad5,2"])   return @"iPadmini4";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhoneSimulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhoneSimulator";
    return platform;
}

@end
